package edu.biwu.req;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

@WebServlet("/req/upload02")
@MultipartConfig
public class ReqUploadDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Collection<Part> uploadFiles = request.getParts();
        for (Part uploadFile : uploadFiles){

            //2.通过Part接口的实现类对象获取上传文件的相关信息
            String fileName = uploadFile.getSubmittedFileName();

            //3.保证存储文件名唯一,可以让用户重复上传文件
            String extensive = fileName.substring(fileName.lastIndexOf('.'));
            String newFileName = UUID.randomUUID() + extensive;

            //4.将上传的文件写入到服务端的某个位置,存储上传文件
            File dir = new File("D:/upload");
            if (!dir.exists()){
                dir.mkdirs();
            }
            uploadFile.write(dir + "/" + newFileName);//直接将上传的文件写入指定位置

        }
        //5.上传成功后,响应上传成功提示
        String collectNewFileName = uploadFiles.stream().map(uploadFile -> uploadFile.getSubmittedFileName())
                .collect(Collectors.joining(","));
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(collectNewFileName + " 文件上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
